package com.vsen.lpr.service.task;

import com.baomidou.mybatisplus.extension.api.R;
import com.vsen.lpr.common.exception.BusinessException;
import com.vsen.lpr.common.model.Response;
import com.vsen.lpr.common.utils.BeanCopyUtil;
import com.vsen.lpr.common.utils.DateTimeUtil;
import com.vsen.lpr.entity.TaskPlan;
import com.vsen.lpr.mapper.TaskPlanMapper;
import com.vsen.lpr.pojo.dto.task.AddTaskDto;
import com.vsen.lpr.pojo.dto.task.EditTaskDto;
import com.vsen.lpr.pojo.dto.task.TaskDto;
import com.vsen.lpr.pojo.vo.task.TaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TaskService {


    @Autowired
    private TaskPlanMapper taskPlanMapper;

    public Response addTask(AddTaskDto dto) throws Exception {
        Integer hour = dto.getHour() == null ? 0 : dto.getHour();
        Integer minute = dto.getMinute() == null ? 0 : dto.getMinute();
        Integer second = dto.getSecond() == null ? 0 : dto.getSecond();
        Long intervalTime = (long) (hour * 3600 + minute * 60 + second) * 1000;
        TaskPlan taskPlan = new TaskPlan();
        BeanCopyUtil.copyFromSrcToDest(dto, taskPlan);
        taskPlan.setIntervalTime(intervalTime);
        taskPlan.setIsRemind(dto.getIsRemind());
        taskPlan.setCreateTime(DateTimeUtil.now());
        taskPlan.setEndTime(DateTimeUtil.parse(dto.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        taskPlan.setRemindTime(DateTimeUtil.parse(dto.getRemindTime(), "yyyy-MM-dd HH:mm:ss"));
        taskPlan.setExecuteTine(DateTimeUtil.parse(dto.getExecuteTine(), "yyyy-MM-dd HH:mm:ss"));
        taskPlanMapper.insert(taskPlan);
        return Response.success();
    }

    public Response delTask(TaskDto dto) {
        Integer result = taskPlanMapper.deleteById(dto.getId());
        if (result > 0) {
            return Response.success();
        } else {
            throw new BusinessException("30002", "删除失败，请联系袁哥");
        }
    }


    public Response<TaskVo> taskDetail(TaskDto dto) {
        TaskPlan taskPlan = taskPlanMapper.selectById(dto.getId());
        if (taskPlan == null) {
            throw new BusinessException("50001", "任务不存在");
        }
        TaskVo taskVo = new TaskVo();
        BeanCopyUtil.copyFromSrcToDest(taskPlan, taskVo);
        return Response.success(taskVo);
    }

    public Response editTask(EditTaskDto dto) throws Exception {
        TaskPlan taskPlan = taskPlanMapper.selectById(dto.getId());
        if (taskPlan == null) {
            throw new BusinessException("50001", "任务不存在");
        }
        ;
        TaskPlan taskPlanDo = new TaskPlan();
        Integer hour = dto.getHour() == null ? 0 : dto.getHour();
        Integer minute = dto.getMinute() == null ? 0 : dto.getMinute();
        Integer second = dto.getSecond() == null ? 0 : dto.getSecond();
        Long intervalTime = (long) (hour * 3600 + minute * 60 + second) * 1000;
        taskPlanDo.setIntervalTime(intervalTime);
        taskPlanDo.setName(dto.getName());
        taskPlanDo.setContext(dto.getContext());
        taskPlanDo.setExecuteTine(DateTimeUtil.parse(dto.getExecuteTine(), "yyyy-MM-dd HH:mm:ss"));
        taskPlanDo.setEndTime(DateTimeUtil.parse(dto.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        taskPlanDo.setRemindTime(DateTimeUtil.parse(dto.getRemindTime(), "yyyy-MM-dd HH:mm:ss"));
        taskPlanDo.setIntervalTime(intervalTime);
        taskPlanDo.setIsRemind(dto.getIsRemind());
        taskPlanDo.setId(taskPlan.getId());
        taskPlanMapper.updateById(taskPlanDo);
        return Response.success();
    }


    public Response ctrlRemind(TaskDto dto) {
        TaskPlan taskPlan = taskPlanMapper.selectById(dto.getId());
        if (taskPlan == null) {
            throw new BusinessException("50001", "任务不存在");
        }
        Integer id = taskPlan.getId();
        String isRemind = "0".equals(taskPlan.getIsRemind()) ? "1" : "0";
        taskPlanMapper.updateIsRemind(id, isRemind);
        return Response.success();
    }

    public Response<List<TaskVo>> taskList(TaskDto dto) {
        List<TaskPlan> taskPlans = taskPlanMapper.selectListByUserId(dto.getUserId());
        List<TaskVo> taskVos = new ArrayList<>();
        for (TaskPlan t : taskPlans) {
            TaskVo taskVo = new TaskVo();
            BeanCopyUtil.copyFromSrcToDest(t, taskVo);
            int intervalTime = Math.toIntExact(t.getIntervalTime() / 1000);
            Integer hour = intervalTime / 3600;
            Integer minute = intervalTime % 3600 / 60;
            Integer second = intervalTime % 3600 % 60;
            taskVo.setHour(hour);
            taskVo.setMinute(minute);
            taskVo.setSecond(second);
            taskVo.setCreateTime(DateTimeUtil.format(t.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            taskVo.setEndTime(DateTimeUtil.format(t.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
            taskVo.setExecuteTine(DateTimeUtil.format(t.getExecuteTine(), "yyyy-MM-dd HH:mm:ss"));
            taskVo.setRemindTime(DateTimeUtil.format(t.getRemindTime(), "yyyy-MM-dd HH:mm:ss"));
            Long now = System.currentTimeMillis();
            Long executeTime = t.getExecuteTine().getTime();
            Integer status;//0 已过期 1进行中 2未开始
            Long endTime = t.getEndTime().getTime();
            if (now < executeTime) {
                status = 1; //未开始
            } else if (now <= endTime) {
                status = 0; //进行中
            } else {
                status = 2; //已过期
            }
            taskVo.setStatus(status);
            taskVos.add(taskVo);
        }

        Collections.sort(taskVos, new Comparator<TaskVo>() {
            @Override
            public int compare(TaskVo o1, TaskVo o2) {
                return o1.getStatus() - o2.getStatus();

            }
        });
        return Response.success(taskVos);
    }


}
